package org.shaitu.wakeremote4j.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Collection;

public class FileUtil {
	
	/**
	 * iterator file line by line
	 * @param file
	 * @param processor
	 */
	public static void lineIterator(File file, StringProcessible processor){
		LineNumberReader reader = null;
		try {
			reader = new LineNumberReader(new FileReader(file));
			String line = reader.readLine();
			while (line != null) {
				processor.process(line);
				line = reader.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
	}
	
	/**
	 * store list to file
	 * @param file
	 * @param beans
	 */
	public static void storeList(File file, Collection beans){
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file));
			if(beans != null){
				for(Object bean:beans){
					writer.write(bean.toString());
					writer.newLine();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
